﻿using Dapper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Linq;
using System.Text;
using Truron.Purchase.Service.DbContext;

namespace Truron.Purchase.Service
{
    public class DbModelService<T> : IDbModelService<T> where T : new()
    {
        /// <summary>
        /// 插入一个
        /// </summary>
        /// <param name="model"></param>
        public int InsertOne(T model, IDbConnection DbConnection)
        {
            if (model == null)
            {
                throw new Exception("插入数据不可为空");
            }
            string pkName = CommonHelper.GetKeyField<T>().ToString();
            string tableName = CommonHelper.GetTableField<T>().ToString();
            var ps = model.GetType().GetProperties();
            List<string> @colms = new List<string>();
            List<string> @params = new List<string>();

            foreach (var p in ps)
            {
                if(p.Name!= pkName && p.CustomAttributes.All(x => x.AttributeType != typeof(NotMappedAttribute)))
                {
                    @colms.Add(string.Format("[{0}]", p.Name));
                    @params.Add(string.Format("@{0}", p.Name));
                }
            }
            var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2}) select @@identity", tableName, string.Join(", ", @colms), string.Join(", ", @params));
            return DbConnection.ExecuteScalar<int>(sql, model);
        }
        public int InsertOne(T model, IDbConnection DbConnection, IDbTransaction DbTransaction)
        {
            if (model == null)
            {
                throw new Exception("插入数据不可为空");
            }
            string pkName = CommonHelper.GetKeyField<T>().ToString();
            string tableName = CommonHelper.GetTableField<T>().ToString();
            var ps = model.GetType().GetProperties();
            List<string> @colms = new List<string>();
            List<string> @params = new List<string>();

            foreach (var p in ps)
            {
                if (p.Name != pkName && p.CustomAttributes.All(x => x.AttributeType != typeof(NotMappedAttribute)))
                {
                    @colms.Add(string.Format("[{0}]", p.Name));
                    @params.Add(string.Format("@{0}", p.Name));
                }
            }
            var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2}) select @@identity", tableName, string.Join(", ", @colms), string.Join(", ", @params));
            return DbConnection.ExecuteScalar<int>(sql, model,DbTransaction);
        }

        public int InsertOne2(T model, IDbConnection DbConnection, IDbTransaction DbTransaction)
        {
            if (model == null)
            {
                throw new Exception("插入数据不可为空");
            }
            string pkName = CommonHelper.GetKeyField<T>().ToString();
            string tableName = CommonHelper.GetTableField<T>().ToString();
            var ps = model.GetType().GetProperties();
            List<string> @colms = new List<string>();
            List<string> @params = new List<string>();

            foreach (var p in ps)
            {
                if (p.Name != pkName && p.CustomAttributes.All(x => x.AttributeType != typeof(NotMappedAttribute)))
                {
                    @colms.Add(string.Format("[{0}]", p.Name));
                    @params.Add(string.Format("@{0}", p.Name));
                }
            }
            var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2}) select @@identity", tableName, string.Join(", ", @colms), string.Join(", ", @params));
            return DbConnection.Execute(sql, model, DbTransaction);
        }
        public int UpdateById(T entity, IDbConnection DbConnection)
        {
            if (entity == null)
            {
                throw new Exception("更新内容不可为空");
            }
           
            string where = "";
            string pkName = CommonHelper.GetKeyField<T>().ToString();
            string tableName = CommonHelper.GetTableField<T>().ToString();
            var listPropert = entity.GetType().GetProperties();
            if (listPropert.Length > 0)
            {
                listPropert.ToList().ForEach(p =>
                {
                    
                    if (pkName == p.Name)
                    {
                        where += $" {p.Name} = @{p.Name} and";
                    }
                });
            }

            where = where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
            if (string.IsNullOrEmpty(where))
            {
                throw new Exception("未找到Id");
            }

            string update = "";
            var listPropertUpdate = entity.GetType().GetProperties();
            if (listPropertUpdate.Length > 0)
            {
                update += "";
                listPropertUpdate.ToList().ForEach(e =>
                {
                    if (e.CustomAttributes.All(x => x.AttributeType != typeof(NotMappedAttribute)) && e.Name!= pkName)
                    {
                        update += $"{e.Name} = @{e.Name} ,";
                    }
                });
            }
            update = update.TrimEnd(',');
            if (string.IsNullOrEmpty(update))
            {
                throw new Exception("无更新内容");
            }
            string query = $"update { tableName} set {update} where {where}";
            return DbConnection.Execute(query, entity);

        }
        public int UpdateById(T entity, IDbConnection DbConnection, IDbTransaction DbTransaction)
        {
            if (entity == null)
            {
                throw new Exception("更新内容不可为空");
            }

            string where = "";
            string pkName = CommonHelper.GetKeyField<T>().ToString();
            string tableName = CommonHelper.GetTableField<T>().ToString();
            var listPropert = entity.GetType().GetProperties();
            if (listPropert.Length > 0)
            {
                listPropert.ToList().ForEach(p =>
                {

                    if (pkName == p.Name)
                    {
                        where += $" {p.Name} = @{p.Name} and";
                    }
                });
            }

            where = where.TrimEnd('d').TrimEnd('n').TrimEnd('a');
            if (string.IsNullOrEmpty(where))
            {
                throw new Exception("未找到Id");
            }

            string update = "";
            var listPropertUpdate = entity.GetType().GetProperties();
            if (listPropertUpdate.Length > 0)
            {
                update += "";
                listPropertUpdate.ToList().ForEach(e =>
                {
                    if (e.CustomAttributes.All(x => x.AttributeType != typeof(NotMappedAttribute)) && e.Name != pkName)
                    {
                        update += $"{e.Name} = @{e.Name} ,";
                    }
                });
            }
            update = update.TrimEnd(',');
            if (string.IsNullOrEmpty(update))
            {
                throw new Exception("无更新内容");
            }
            string query = $"update { tableName} set {update} where {where}";
            return DbConnection.Execute(query, entity, DbTransaction);

        }
        //public int Delete(T entiy, int[] Ids, IDbConnection DbConnection)
        //{
        //    string pkName = CommonHelper.GetKeyField<T>().ToString();
        //    string tableName = CommonHelper.GetTableField<T>().ToString();
        //    string query = $"update { tableName} set  where {pkName} in @Id ";
        //    string sql = "UPDATE [dbo].[Crm_Contacts] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id in @Id";
        //    return DbConnection.Execute(query, entity);
        //    string sql = "UPDATE [dbo].[Crm_Contacts] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id in @Id";
        //    delCount = conn.Execute(sql, new { Status = Status.delete, LastUpdateUser = userId, LastUpdateTime = DateTime.Now, Id = Ids });
        //}
    }
}
